package Handler;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import Exception.InvalidFormatException;
import Exception.InvalidTypeFormatException;
import formatter.FormatterJson;
import formatter.FormatterTrad;
import formatter.IFormatter;
import logging.Record;

public class FileHandler extends Handler{

	String path;
	FileWriter logFile;
	BufferedWriter writer;
	
	public FileHandler(String pathLog) {
		super();
		this.path = pathLog;
		this.logFile = null;
		this.writer = null;
	}

	/*
	 * write message in file according to associated format
	 */
	@Override
	public void write(Record record){
		try {
			logFile = new FileWriter(path, true);
			writer = new BufferedWriter(logFile);
			IFormatter formatter = new FormatterTrad(record.getFormatFile());
			formatter.setChainFormatter(new FormatterJson(record.getFormatFile()));
			try {
				String messageFormatted = formatter.applyFormat(record);
				record.setMessage(messageFormatted);
				if (messageCanWrite(record)){
					writer.write(messageFormatted);
					writer.newLine();	
				}
			} catch (InvalidFormatException
					| InvalidTypeFormatException e) {
				e.printStackTrace();
			}
			
			writer.close();
			logFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getName() {
		return path;
	}

}
